﻿using AutoMapper;
using DongFangGuoKai.WMSPlatform.Core;
using DongFangGuoKai.WMSPlatform.Domain.Model;
using DongFangGuoKai.WMSPlatform.Service.User.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace DongFangGuoKai.WMSPlatform.Service.User
{
    public class UserService:IUserService
    {
        private readonly SimpleRepositroy<TUsers> userrepost;
        private readonly SimpleRepositroy<TUserRoles> userRolerepost;

        public UserService(SimpleRepositroy<TUsers> userrepost)
        {
            this.userrepost = userrepost;

            userRolerepost = userrepost.ChangeRepository<SimpleRepositroy<TUserRoles>>();
        }

        /// <summary>
        /// 判断登录
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public TUsers GetLogin(LoginPDADTO pDADTO)
        {
            try
            {
                var obj = userrepost.GetFirst(x => x.UserName == pDADTO.LoginName);
                if (obj != null)
                {
                    //MD5加密
                    pDADTO.LoginPwd = MD5Encrypt16(pDADTO.LoginPwd);
                    if (obj.Pwd == pDADTO.LoginPwd && obj.Status == 1)
                    {
                        return obj;
                    }
                }
                return null;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 16位MD5加密
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string MD5Encrypt16(string password)
        {
            var md5 = MD5.Create();
            string t2 = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(password)), 4, 8);
            t2 = t2.Replace("-", string.Empty);
            return t2;
        }

        /// <summary>
        /// 用户显示
        /// </summary>
        /// <param name="uname"></param>
        /// <param name="rid"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TUsers> GetUserList(string uname, int rid, int state, int pageIndex, int pageSize, out int totalCount)
        {
            try
            {
                //去除跟踪状态-提高查询速度
                var ulist = userrepost.GetList();
                if (!string.IsNullOrEmpty(uname))
                {
                    ulist = ulist.Where(x => x.UserName.Contains(uname)).ToList();
                }

                if (state != 3)
                {
                    ulist = ulist.Where(x => x.Status == state).ToList();
                }

                var urlist = userRolerepost.GetList();

                if (rid != 0)
                {
                    urlist = urlist.Where(x => x.RoleId == rid).ToList();
                }

                var list = (from u in ulist
                            join ur in urlist
                            on u.Id equals ur.UserId
                            select u).Distinct();
                totalCount = list.Count();
                return list.OrderBy(x => x.CreateDate).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddUser(UserRoleDto m)
        {
            //使用事务的原子性
            try
            {
                userrepost.AsTenant().BeginTran();
                var obj = userrepost.GetFirst(x => x.UserName == m.UserName);
                if (obj != null)
                {
                    return false;
                }
                //添加用户
                TUsers user = new TUsers();
                user.UserName = m.UserName;
                user.Pwd = m.Pwd;
                user.Email = m.Email;
                user.MobilePhone = m.MobilePhone;
                user.IsModifyPwd = m.IsModifyPwd;
                user.ModifyUserId = m.ModifyUserId;
                user.UserSecret = m.UserSecret;
                user.Remark = m.Remark;
                user.DepartmentId = m.DepartmentId;
                user.JobNo = m.JobNo;
                user.RealName = m.RealName;
                user.Status = m.Status;
                user.Signature = m.Signature;
                user.Pwd = MD5Encrypt16(user.Pwd);
                user.CreateUserId = m.NowUserId;
                user.CreateUserName = m.RealName;
                user.CreateDate = DateTime.Now;
                user.ModifyDate = DateTime.Now;
                user.ModifyUserName = m.RealName;
                user.ModifyUserId = m.NowUserId;
                user.Id = userrepost.InsertReturnIdentity(user);
                if (user.Id <= 0)
                {
                    userrepost.AsTenant().RollbackTran();
                    return false;
                }
                //循环遍历角色
                foreach (var item in m.RoleIds.Split(','))
                {
                    TUserRoles ur = new TUserRoles();
                    ur.UserId = user.Id;
                    ur.RoleId = Convert.ToInt32(item);
                    if (!userRolerepost.Insert(ur))
                    {
                        userrepost.AsTenant().RollbackTran();
                        return false;
                    }
                }
                userrepost.AsTenant().CommitTran();
                return true;
            }
            catch (Exception)
            {
                //事务回滚
                userrepost.AsTenant().RollbackTran();
                throw;
            }
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool DelUser(int uid)
        {
            try
            {
                userrepost.AsTenant().BeginTran();
                var uobj = userrepost.GetFirst(u=>u.Id == uid);
                if (uobj != null)
                {
                    if (!userrepost.Delete(uobj))
                    {
                        userrepost.AsTenant().RollbackTran();
                        return false;
                    }
                  
                    var urlist = userRolerepost.GetList(x => x.UserId == uid);
                    if (!userRolerepost.Delete(urlist))
                    {
                        userrepost.AsTenant().RollbackTran();
                        return false;
                    }
                    userrepost.AsTenant().CommitTran();
                    return true;
                }
                userrepost.AsTenant().RollbackTran();
                return false;
            }
            catch (Exception)
            {
                userrepost.AsTenant().RollbackTran();
                throw;
            }
        }

        /// <summary>
        /// 批量删除用户
        /// </summary>
        /// <param name="ulist"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool DelUsers(List<TUsers> ulist)
        {
            try
            {
                userrepost.AsTenant().BeginTran();
                if (ulist != null)
                {
                    if (!userrepost.Delete(ulist))
                    {
                        userrepost.AsTenant().RollbackTran();
                        return false;
                    }
                    foreach (var item in ulist)
                    {
                        var urlist = userRolerepost.GetList(x => x.UserId == item.Id);
                        if (!userRolerepost.Delete(urlist))
                        {
                            userrepost.AsTenant().RollbackTran();
                            return false;
                        }
                    }
                    userrepost.AsTenant().CommitTran();
                    return true;
                }
                userrepost.AsTenant().RollbackTran();
                return false;
            }
            catch (Exception)
            {
                userrepost.AsTenant().RollbackTran();
                throw;
            }
        }

        /// <summary>
        /// 根据主键获取用户Id
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public UserRoleDto URById(int uid)
        {
            try
            {
                var uobj = userrepost.GetFirst(u=>u.Id == uid);
                if (uobj != null)
                {
                    UserRoleDto urdto = new UserRoleDto();
                    urdto.Status = uobj.Status;
                    urdto.Email = uobj.Email;
                    urdto.UserName = uobj.UserName;
                    urdto.Gender = uobj.Gender;
                    urdto.CreateDate = uobj.CreateDate;
                    urdto.JobNo = uobj.JobNo;
                    urdto.Pwd = uobj.Pwd;
                    urdto.UserName = uobj.UserName;
                    urdto.UserSecret = uobj.UserSecret;
                    urdto.RealName = uobj.RealName;
                    var ur = userRolerepost.GetList(x => x.UserId == uid);
                    if (ur.Count() > 0)
                    {
                        foreach (var item in ur)
                        {
                            urdto.RoleIds += item.RoleId + ",";
                        }
                        urdto.RoleIds = urdto.RoleIds.TrimEnd(',');
                    }
                    return urdto;
                }
                return null;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdUser(UserRoleDto m)
        {
            try
            {
                userrepost.AsTenant().BeginTran();
                var list = userrepost.GetFirst(x => x.Id != m.Id && x.UserName == m.UserName);
                if (list != null)
                {
                    return false;
                }
                //更新要修改的信息
                TUsers user = new TUsers();
                user.UserName = m.UserName;
                user.Pwd = m.Pwd;
                user.Email = m.Email;
                user.MobilePhone = m.MobilePhone;
                user.IsModifyPwd = m.IsModifyPwd;
                user.ModifyUserId = m.ModifyUserId;
                user.UserSecret = m.UserSecret;
                user.Remark = m.Remark;
                user.DepartmentId = m.DepartmentId;
                user.JobNo = m.JobNo;
                user.RealName = m.RealName;
                user.Status = m.Status;
                user.Signature = m.Signature;
                user.Pwd = MD5Encrypt16(user.Pwd);
                user.CreateUserId = m.NowUserId;
                user.CreateUserName = m.RealName;
                user.CreateDate = DateTime.Now;
                user.ModifyDate = DateTime.Now;
                user.ModifyUserName = m.RealName;
                user.ModifyUserId = m.NowUserId;
                if (!userrepost.Update(user))
                {
                    userrepost.AsTenant().RollbackTran();
                    return false;
                }

                //获取当前用户的所有角色
                var urlist = userRolerepost.GetList(x => x.UserId == user.Id);
                if (urlist.Count() > 0)
                {
                    if (!userRolerepost.Delete(urlist))
                    {
                        userrepost.AsTenant().RollbackTran();
                        return false;
                    }
                }

                foreach (var item in m.RoleIds.Split(','))
                {
                    TUserRoles userRole = new TUserRoles();
                    userRole.UserId = m.Id;
                    userRole.RoleId = Convert.ToInt32(item);
                    if (!userRolerepost.Insert(userRole))
                    {
                        userrepost.AsTenant().RollbackTran();
                        return false;
                    }
                }
                userrepost.AsTenant().CommitTran();
                return true;
            }
            catch (Exception)
            {
                //事务回滚
                userrepost.AsTenant().RollbackTran();
                throw;
            }
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public bool UserResetPwd(ResetPwdDto m)
        {
            try
            {
                var obj = userrepost.GetFirst(u=>u.Id == m.uid);
                if (obj != null)
                {
                    obj.ModifyUserId = m.NowUserId;
                    obj.ModifyUserName = m.NowUserRealName;
                    obj.ModifyDate = DateTime.Now;
                    obj.Pwd = "8AD9902AECBA32E2";
                    if (!userrepost.Update(obj))
                    {
                        return false;
                    }
                }
                return true;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UserModifyPwd(ModifyPwdDto m)
        {
            try
            {
                var uobj = userrepost.GetFirst(u => u.Id == m.NowUserId);

                if (uobj != null)
                {
                    m.NowPwd = MD5Encrypt16(m.NowPwd);
                    if (uobj.Pwd == m.NowPwd)
                    {
                        m.NewPwd = MD5Encrypt16(m.NewPwd);
                        uobj.Pwd = m.NewPwd;
                        uobj.ModifyDate = DateTime.Now;
                        if (!userrepost.Update(uobj))
                        {
                            return false;
                        }
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                return false;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 修改用户状态
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public bool UpdUserStatus(UpdStatusDto m)
        {
            var uobj = userrepost.GetFirst(u => u.Id == m.Id);
            if (uobj != null)
            {
                int? status = uobj.Status;
                if (status == 0)
                {
                    uobj.Status = 1;
                }
                else
                    uobj.Status = 0;

                uobj.ModifyUserId = m.NowUserId;
                uobj.ModifyUserName = m.NowUserRealName;
                uobj.ModifyDate = DateTime.Now;
                if (!userrepost.Update(uobj))
                {
                    return false;
                }
                return true;
            }
            return false;
        }
    }
}
